import React from 'react'
import { connect } from 'react-redux'
import config from "config";
import moment from 'moment'
import { deepCopy, deepFullCopy, messages } from "share/common";
import { Table, message, Button, Modal, Alert, Select } from 'antd';
import SearchArea from 'components/search-area';
import 'styles/financial-management/entry-information.scss';
import Control from 'components/control'
import financialService from "containers/financial-management/financialService";
import ExportModal from 'components/template/export-modal/export-modal';
const Option = Select.Option;

class EntryDetail extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      searchForm: [
        {
          type: 'select', id: 'setOfBooksId', label: messages('financial-management.key345')/*账套*/, options: [], method: 'get',
          valueKey: 'id', labelKey: 'setOfBooksName', getParams: {roleType: 'TENANT'},
          getUrl: `${config.baseUrl}/api/setOfBooks/by/tenant`,
          defaultValue: {
            label: props.company.setOfBooksName,
            key: props.company.setOfBooksId
          }, allowClear: false,
          event: 'CHANGE_TYPE'
        },{
          type: 'list', id: 'companyId', label: messages('financial-management.key588')/*公司*/, labelKey: 'name',
          valueKey: 'id', listType: 'permission_company', listExtraParams:{enabled: true}, single: true
        },{
          type: 'input', id: 'businessCode', label: messages('financial-management.key286')/*单据编号*/, placeholder: messages('common.please.enter') + messages('financial-management.key286')/*单据编号*/
        },{
          type: 'list', id: 'functionDefineId', label: messages('financial-management.key625')/*核算业务类型*/, labelKey: 'typeName', valueKey: 'id',
          listType: 'choose_function_define', listExtraParams: {setOfBooksId: props.company.setOfBooksId}, single: true
        },{
          type: 'items', id: 'dateRange',
          items: [
            {type: 'date', id: 'periodSetFrom', label: messages('financial-management.key626')/*凭证期间从*/},
            {type: 'date', id: 'periodSetTo', label: messages('financial-management.key627')/*凭证期间到*/}
          ]
        },{
          type: 'items', id: 'thingRange',
          items: [
            {type: 'date', id: 'transactionDateStart', label: messages('financial-management.key628')/*事务日期从*/, defaultValue: moment().subtract(1, 'month')},
            {type: 'date', id: 'transactionDateTo', label: messages('financial-management.key629')/*事务日期到*/, defaultValue: moment()}
          ]
        },{
          type: 'items',
          id: 'objectRange',
          items: [
            {
              type: 'list', id: 'accountCodeFrom', label: messages('financial-management.key630')/*科目代码从*/, labelKey: 'accountCode', valueKey: 'accountCode',
              listType: 'select_object', listExtraParams: {setOfBooksId: props.company.setOfBooksId}, single: true
            },
            {
              type: 'list', id: 'accountCodeTo', label: messages('financial-management.key631')/*科目代码到*/, labelKey: 'accountCode', valueKey: 'accountCode',
              listType: 'select_object', listExtraParams: {setOfBooksId: props.company.setOfBooksId}, single: true
            }
          ]
        },{
          type: 'select', id: 'currencyCode', label: messages('common.currency')/*币种*/, options: [],
          getUrl: `${config.baseUrl}/api/company/standard/currency/getAll`,
          labelKey: 'currency', valueKey: 'currency', method: 'get'
        },{
          type: 'input', id: 'documentCode', label: messages('financial-management.key170')/*凭证编号*/
        },{
          type: 'select', id: 'importFlag', label: messages('financial-management.key632')/*导入标志*/, options: [
            {label: messages('financial-management.key641')/*未导入*/, value: '1001'},
            {label: messages('financial-management.key642')/*导入中*/, value: '1002'},
            {label: messages('financial-management.key643')/*已导入*/, value: '1003'},
            {label: messages('financial-management.key644')/*导入失败*/, value: '1004'}
          ]
        },{
          type: 'date',id: 'importDate', label: messages('financial-management.key633')/*导入日期*/
        }
      ],
      searchParams: {
        setOfBooksId: props.company.setOfBooksId,
        transactionDateStart: moment(moment().subtract(1, 'month').format('YYYY-MM-DD 00:00:00')).utc(),
        transactionDateTo: moment(moment().format('YYYY-MM-DD 23:59:59')).utc()
      },
      columns: [
        {title: messages('financial-management.key345')/*账套*/,dataIndex: 'setOfBooksName'},
        {title: messages('financial-management.key170')/*凭证编号*/,dataIndex: 'documentCode'},
        {title: messages('financial-management.key625')/*核算业务类型*/,dataIndex: 'functionDefineCode'},
        {title: messages('financial-management.key286')/*单据编号*/,dataIndex: 'businessCode'},
        {title: messages('financial-management.key588')/*公司*/,dataIndex: 'companyName'},
        {title: messages('financial-management.key634')/*事务日期*/,dataIndex: 'transactionDate', render: value => moment(value).format('YYYY-MM-DD HH:mm:ss')},
        {title: messages('financial-management.key635')/*凭证期间*/,dataIndex: 'periodSet'},
        {title: messages('financial-management.key405')/*币种*/,dataIndex: 'currencyCode'},
        {title: messages('financial-management.key610')/*摘要*/,dataIndex: 'remark'},
        {title: messages('financial-management.key636')/*会计科目*/,dataIndex: 'accountCode', render: (value,record) => `${value}-${record.accountName}`},
        {title: messages('financial-management.key637')/*借方原币金额*/,dataIndex: 'debitAmount'},
        {title: messages('financial-management.key638')/*贷方原币金额*/,dataIndex: 'creditAmount'},
        {title: messages('financial-management.key639')/*借方本币金额*/,dataIndex: 'debitBaseAmount'},
        {title: messages('financial-management.key640')/*贷方本币金额*/,dataIndex: 'creditBaseAmount'},
        {title: messages('financial-management.key632')/*导入标志*/, dataIndex: 'importFlag', render: (value) => {
            return value === 1001 ? messages('financial-management.key641')/*未导入*/ : (value === 1002 ? messages('financial-management.key642')/*导入中*/ : (value === 1003 ? messages('financial-management.key643')/*已导入*/ : messages('financial-management.key644')/*导入失败*/));
          }
        },
        {title: messages('financial-management.key633')/*导入日期*/,dataIndex: 'importDate', render: value => value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-'}
      ],
      data: [],
      loading: false,
      pagination: {
        total: 0
      },
      page: 0,
      modalVisible: false,
      batchBtnLoading: false,
      batchSize: 999
    }
  }

  componentDidMount() {
    this.getList();
  }

  getList = () => {
    const { searchParams, page } = this.state;
    const { loginUser } = this.props;
    let temp = deepCopy(searchParams);
    temp.page = page;
    temp.tenantId = loginUser.tenantId;
    temp.operatorId = loginUser.id;
    this.setState({loading: true});
    financialService.getEntryList(temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager,
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  search = (values) => {
    let temp = deepCopy(values);
    Object.keys(temp).map(item => {
      !temp[item] && delete temp[item];
    });
    temp.periodSetFrom && (temp.periodSetFrom = moment(temp.periodSetFrom.format('YYYY-MM-DD 00:00:00')).utc());
    temp.periodSetTo && (temp.periodSetTo = moment(temp.periodSetTo.format('YYYY-MM-DD 23:59:59')).utc());
    temp.transactionDateStart && (temp.transactionDateStart = moment(temp.transactionDateStart.format('YYYY-MM-DD 00:00:00')).utc());
    temp.transactionDateTo && (temp.transactionDateTo = moment(temp.transactionDateTo.format('YYYY-MM-DD 23:59:59')).utc());
    temp.companyId && (temp.companyId = temp.companyId[0]);
    temp.functionDefineId && (temp.functionDefineId = temp.functionDefineId[0]);
    temp.accountCodeFrom && (temp.accountCodeFrom = temp.accountCodeFrom[0].accountCode);
    temp.accountCodeTo && (temp.accountCodeTo = temp.accountCodeTo[0].accountCode);
    temp.importFlag && (temp.importFlag = Number(temp.importFlag));
    this.setState({searchParams: temp},() => {
      this.getList();
    })
  };

  clear = () => {
    this.setState({searchParams: {setOfBooksId: this.props.company.setOfBooksId}}, () => {
      this.getList();
    })
  };

  searchEventHandle = (event, value) => {
    switch (event) {
      case 'CHANGE_TYPE': {
        this.formRef.setValues({
          accountCodeFrom: '',
          accountCodeTo: '',
          functionDefineId: ''
        });
        const { searchForm } = this.state;
        searchForm.map(item => {
          if(item.id === 'objectRange'){
            item.items.map(record => {
              record.listExtraParams = {
                setOfBooksId: value
              };
            })
          } else if (item.id === 'functionDefineId'){
            item.listExtraParams = {
              setOfBooksId: value
            };
          }
        });
        break;
      }
    }
  };

  toGenerateExpenseBatch = () => {
    const { loginUser, company, makeBatchDone } = this.props;
    this.setState({ batchBtnLoading: true });
    let params = deepFullCopy(this.state.searchParams);
    params.batchLimit = this.state.batchSize;
    params.tenantId = loginUser.tenantId;
    params.operatorOid = loginUser.userOID;
    params.operatorEmployeeId = loginUser.employeeID;
    params.operatorName = loginUser.fullName;
    params.setOfBooksName = company.setOfBooksName;
    params.operatorId = loginUser.id;
    financialService.makeBatch(params).then(() => {
      message.success(messages('financial-management.key601')/*批次生成成功*/);
      this.setState({ batchBtnLoading: false, modalVisible: false },() => {
        makeBatchDone();
      });
      this.getList()
    }).catch(e => {
      this.setState({ batchBtnLoading: false, modalVisible: false });
      message.error(e.response.data.message);
    })
  };

  render(){
    const { searchForm, columns, pagination, data, loading, modalVisible, batchBtnLoading, batchSize } = this.state;
    let noticeMessage = messages('financial-management.key842')/*生成批次后，分录的<span class='color-blue'>导入标志</span>将会变为已导入，列表中未导入的分录可生成批次。*/;
    return(
      <Control>
        <div className="entry-information">
          <SearchArea
            searchForm={searchForm}
            wrappedComponentRef={inst => this.formRef = inst}
            eventHandle={this.searchEventHandle}
            submitHandle={this.search}
            clearHandle={this.clear}
          />
          <div className="table-header">
            <div className="table-header-buttons">
              {/*<ExportModal*/}
              {/*  type={"btn"}*/}
              {/*  btnType="primary"*/}
              {/*  style={{ display: 'inline-block' }}*/}
              {/*  exportTitle={messages('financial-management.key146')}*/}
              {/*  exportType="BILL_CHECK"*/}
              {/*  exportCondition={{*/}
              {/*    billCheckSearchCommand: this.state.searchParams*/}
              {/*  }}*/}
              {/*  data-control={'entry-information.hidden'}*/}
              {/*  exportCommand={'EXP_OR_LOANBILL'}*/}
              {/*/>*/}
              <Button data-control={'entry-information.hidden'} onClick={() => this.setState({modalVisible: true})}>{messages('financial-management.key33')/*生成批次*/}</Button>
            </div>
          </div>
          <Alert
            type="info" showIcon
            message={<div dangerouslySetInnerHTML={{__html: noticeMessage}}/>}
          />
          <Table
            pagination={pagination}
            dataSource={data}
            loading={loading}
            bordered
            rowKey={'id'}
            className={'large-table'}
            scroll={{ x: true }}
            columns={columns}
          />
          <div className="modal-container"/>
          <Modal
            visible={modalVisible}
            title={messages('financial-management.key33')/*生成批次*/}
            getContainer={() => document.getElementsByClassName('modal-container')[0]}
            footer={[
              <Button key="cancel"
                      onClick={() => this.setState({ modalVisible: false })}>
                {messages('common.cancel')}
              </Button>,
              <Button key="ok"
                      type="primary"
                      loading={batchBtnLoading}
                      onClick={this.toGenerateExpenseBatch}>
                {messages('common.ok')}
              </Button>,
            ]}
            onCancel={() => this.setState({ modalVisible: false })}
          >
            <Alert
              type="info" showIcon
              message={messages('financial-management.key843')/*当批次中数量过大，可能导致下游导入失败，请根据您的财务系统进行选择。推荐：999条分录/批*/}
            />
            <div style={{marginTop: '10px'}}> {messages('financial-management.key31')/*设置打印批次*/} :
              <Select value={batchSize} onChange={value => this.setState({batchSize: value}) }>
                <Option value={999}>999</Option>
                <Option value={9999}>9999</Option>
                <Option value={99999}>99999</Option>
              </Select>
              / {messages('financial-management.key32')/*批*/}
            </div>
          </Modal>
        </div>
      </Control>
    )
  }
}

function mapStateToProps(state){
  return {
    company: state.login.company,
    loginUser: state.login.loginUser
  }
}

export default connect(mapStateToProps)(EntryDetail);
